package nio;


import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * 一、缓冲区类型
 * ByteBuffer
 * CharBuffer
 * ShortBuffer
 * IntBuffer
 * LongBuffer
 * FloatBuffer
 * DoubleBuffer
 *
 * 管理方式几乎一致，通过allocate()创建缓冲区
 *
 * 二、Buffer的核心属性
 * 1. capacity：Buffer的容量，固定不变
 * 2. position：即将放置数据的位置
 * 3. limit：读数据边界[position, limit)
 * 4. mark：标记当前position的位置，之后position可以通过reset()恢复到mark位置
 * mark <= position <= limit <= capacity
 *
 */
public class BufferDemo {

    @Test
    public void testDir() {
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    }

    @Test
    public void test() {
        // 1. 分配空间
        ByteBuffer buf = ByteBuffer.allocate(1024);
        System.out.println("----------allocate()------------");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        // 2. put放入数据
        buf.put("hello".getBytes());
        System.out.println("-----------put()----------");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        // 3. flip切换到读模式
        buf.flip();
        System.out.println("-----------flip()----------");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //4. 读取数据
        byte[] dst = new byte[buf.limit()];
        buf.get(dst);
        System.out.println("-----------get(dst)----------");
        System.out.println(new String(dst));
        System.out.println("-----------after get----------");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //5. rewind() : 重复读数据
        buf.rewind();
        System.out.println("-----------rewind()-----------");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //6. clear() : 清空缓冲区, 数据并没有被清空，只是指针复位
        buf.clear();
        System.out.println("-----------clear()-----------");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());
    }
}
